package de.gameduell.net.src.protocol {

	import de.gameduell.net.src.body.BodyFactory;
	import de.gameduell.net.src.body.IBody;
	import de.gameduell.net.src.encryption.EncryptionFactory;
	import de.gameduell.net.src.encryption.IEncryption;
	import de.gameduell.net.src.hashing.HashFactory;
	import de.gameduell.net.src.hashing.IHashing;
	import de.gameduell.net.src.header.HeaderFactory;
	import de.gameduell.net.src.header.IHeader;
	import de.gameduell.net.src.message.IMessage;
	import de.gameduell.net.src.message.MessageFactory;

	public class Protocol_V2 implements IProtocol {

		private const HEADER_TYPE:int 	  = HeaderFactory.V3;
		private const BODY_TYPE:int	 	  = BodyFactory.V2;
		private const HASH_TYPE:int	 	  = HashFactory.MD5;
		private const ENCRYPTION_TYPE:int = EncryptionFactory.SHUFFLE;
		private const MESSAGE_TYPE:int	  = MessageFactory.V2;
		
		private var headerFactory:HeaderFactory;
		private var hashFactory:HashFactory;
		private var bodyFactory:BodyFactory;
		private var encryptionFactory:EncryptionFactory;
		private var messageFactory:MessageFactory;
		private var hashing:IHashing;
		private var encryption:IEncryption;
		private var serviceType:String;
		private var slotId:String;
		private var ticket:String;

		public function Protocol_V2() {
			headerFactory 	  = new HeaderFactory();
			hashFactory	  	  = new HashFactory();
			bodyFactory   	  = new BodyFactory();
			encryptionFactory = new EncryptionFactory();
			messageFactory	  = new MessageFactory();
			
			hashing	   		  = hashFactory.createHash(HASH_TYPE);
			encryption		  = encryptionFactory.createEncryption(ENCRYPTION_TYPE);	
		}
		
		public function init(aServiceType:String, aSlotId:String, aTicket:String):void{
			serviceType = aServiceType;
			slotId		= aSlotId;
			ticket		= aTicket;
		}
		
		public function createMessage(aRequestType:String, parameters:Array, id:int):IMessage {
			var header:IHeader = headerFactory.createHeader(HEADER_TYPE,BODY_TYPE,serviceType,slotId,id,ticket);			
			var body:IBody 	   = bodyFactory.createBody(BODY_TYPE,aRequestType,parameters,hashing,encryption);
			
			return  messageFactory.createMessage(MESSAGE_TYPE, header, body);
		}
		
		public function extractMessages(data:String):Array {	
			var dataList:Array 		 = decodeURIComponent(data).split("\n"); 
					
			var headerContent:String = dataList.shift();
			var bodyContent:String 	 = dataList.join("\n");
   			
   			var header:IHeader = headerFactory.extractHeader(HEADER_TYPE, headerContent, serviceType, slotId, ticket);
   			var bodies:Array   = bodyFactory.extractBodies(BODY_TYPE, bodyContent, hashing,encryption);
   			
   			var messages:Array = new Array();
   			for(var i:int = 0; i<bodies.length;i++){
   				messages.push(messageFactory.createMessage(MESSAGE_TYPE,header, bodies[i]));
   			}
   			
			return  messages;
		}
	}
}
